要實現Form表單功能需用到兩個handlers:
import UIKit
import GCDWebServer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let webServer = GCDWebServer()
webServer.addHandler(forMethod: "GET", path: "/", request: GCDWebServerRequest.self, processBlock: { (request) -> GCDWebServerResponse? in
let html = "<html><body>" +
"<form name=\"input\" action=\"/\" method=\"post\" " +
"enctype=\"application/x-www-form-urlencoded\"> " +
"用户名: <input type=\"text\" name=\"username\">" +
"<input type=\"submit\" value=\"提交\">" +
"</form>" +
"</body></html>"
return GCDWebServerDataResponse(html: html)
});
//处理post请求:/(获取提交的表单数据,并返回结果)
webServer.addHandler(forMethod: "POST", path: "/", request: GCDWebServerURLEncodedFormRequest.self, processBlock: { (request) -> GCDWebServerResponse? in
let formRequest = request as! GCDWebServerURLEncodedFormRequest
let value = formRequest.arguments["username"]
let html = "<html><body>\(String(describing: value))</body></html>"
return GCDWebServerDataResponse(html: html)
});
webServer.start(withPort: 8080, bonjourName: "GCD Web Server")
print("服务启动成功,使用你的浏览器访问:\(webServer.serverURL!)")
}
}